//
//  ShopMallSearchVC.m
//  YBLive
//
//  Created by ybRRR on 2020/8/20.
//  Copyright © 2020 cat. All rights reserved.
//

#import "ShopMallSearchVC.h"
#import "HXSearchBar.h"
#import "ShopCell.h"
#import "SearchHorizontalCell.h"
#import "OutsideGoodsDetailVC.h"
#import "CommodityDetailVC.h"

@interface ShopMallSearchVC ()<UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
{
    UIView *navi;
    HXSearchBar *searchBars;

    UIView *selBtnView;
    UIButton *newBtn;
    UIButton *sellBtn;
    UIButton *priceBtn;
    UIButton *changeUIBtn;

    BOOL isVertical;
    BOOL sellIsUp;
    BOOL priceIsUp;

    NSString *searchStr;
    NSString *sellSortStr;
    NSString *priceSortStr;
    NSString *isnew;

    UICollectionViewFlowLayout *flow;
    
    int pageIndex;
}
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *infoArray;

@end

@implementation ShopMallSearchVC


#pragma  mark-------请求数据----------------
-(void)requestListData{
    
    NSLog(@"shopmallDetail-----classId:%@  \n sellSort:%@ \n priceSort:%@ \n isnew:%@",searchBars.text,sellSortStr,priceSortStr,isnew);
    
    [WYNetworking postWithUrl:@"Home.searchShop" Dic:@{@"key":searchBars.text,@"sell":sellSortStr,@"price":priceSortStr,@"isnew":isnew,@"p":@(pageIndex)} Suc:^(int code, id info, NSString *msg) {
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];
        if (code == 0) {
            NSArray *list =info;
            if (pageIndex == 1) {
                [_infoArray removeAllObjects];
            }
            [_infoArray addObjectsFromArray:list];
            [_collectionView reloadData];
            if (_infoArray.count < 1) {
                [PublicView showTextNoData:_collectionView text1:YZMsg(@"暂无商品") text2:@"" centerY:0.8];
            }else{
                [PublicView hiddenTextNoData:_collectionView];
            }
        if (list.count == 0) {
            [_collectionView.mj_footer endRefreshingWithNoMoreData];
        }
    }
        

        } Fail:^(id fail) {
            [_collectionView.mj_header endRefreshing];
            [_collectionView.mj_footer endRefreshing];

        }];
//    [YBToolClass postNetworkWithUrl:@"Home.searchShop" andParameter:@{@"key":searchBars.text,@"sell":sellSortStr,@"price":priceSortStr,@"isnew":isnew,@"p":@(pageIndex)} success:^(int code,id info,NSString *msg) {
//            [_collectionView.mj_header endRefreshing];
//            [_collectionView.mj_footer endRefreshing];
//            if (code == 0) {
//                NSArray *list =info;
//                if (pageIndex == 1) {
//                    [_infoArray removeAllObjects];
//                }
//                [_infoArray addObjectsFromArray:list];
//                [_collectionView reloadData];
//                if (_infoArray.count < 1) {
//                    [PublicView showTextNoData:_collectionView text1:YZMsg(@"暂无商品") text2:@""];
//                }else{
//                    [PublicView hiddenTextNoData:_collectionView];
//                }
//            if (list.count == 0) {
//                [_collectionView.mj_footer endRefreshingWithNoMoreData];
//            }
//        }
//
//        } fail:^{
//            [_collectionView.mj_header endRefreshing];
//            [_collectionView.mj_footer endRefreshing];
//        }];
}

-(void)initData{
    self.infoArray = [NSMutableArray array];
    sellSortStr = @"";
    priceSortStr = @"";
    isnew = @"0";
    searchStr = @"";
    pageIndex = 1;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = RGB(250, 250, 250);
    [self initData];
    
    [self addSearchBar];
    [self setSelClassBtn];
    [self createCollectionView];
}

#pragma mark--------添加搜索条---------begin--------
- (void)addSearchBar {
    navi = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 64+statusbarHeight+10)];
    navi.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:navi];
    
    //加上 搜索栏
    searchBars = [[HXSearchBar alloc] initWithFrame:CGRectMake(10,10 + statusbarHeight, _window_width-20,60)];
    searchBars.backgroundColor = [UIColor whiteColor];
    searchBars.delegate = self;
    //输入框提示
    searchBars.placeholder = YZMsg(@"请输入您要搜索的商品名称");
    //光标颜色
    searchBars.cursorColor = Pink_Cor;
    //TextField
    searchBars.searchBarTextField.layer.cornerRadius = 16;
    searchBars.searchBarTextField.layer.masksToBounds = YES;
    searchBars.searchBarTextField.backgroundColor = RGB(241, 241, 241);
    searchBars.searchBarTextField.clearButtonMode = UITextFieldViewModeNever;

    //去掉取消按钮灰色背景
    searchBars.hideSearchBarBackgroundImage = YES;
    searchBars.searchBarTextField.font = [UIFont systemFontOfSize:14];
    searchBars.cancleButton.backgroundColor = [UIColor clearColor];
    [searchBars.cancleButton setTitle:YZMsg(@"取消") forState:UIControlStateNormal];
    [searchBars.cancleButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    searchBars.cancleButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [navi addSubview:searchBars];
    [[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTintColor:[UIColor grayColor]];
    [searchBars becomeFirstResponder];

}
//已经开始编辑时的回调
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
//    HXSearchBar *sear = (HXSearchBar *)searchBar;
//    //取消按钮
//    sear.cancleButton.backgroundColor = [UIColor clearColor];
//    [sear.cancleButton setTitle:YZMsg(@"取消") forState:UIControlStateNormal];
//    [sear.cancleButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//    sear.cancleButton.titleLabel.font = [UIFont systemFontOfSize:14];

}
//搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [_infoArray removeAllObjects];
    [_collectionView reloadData];
    pageIndex = 1;
    [self requestListData];
    [searchBar resignFirstResponder];

}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [_infoArray removeAllObjects];
    [_collectionView reloadData];
    pageIndex = 1;
    [self requestListData];

}
//取消按钮点击的回调
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
//    searchBar.showsCancelButton = NO;
    searchBar.text = nil;
    [self.view endEditing:YES];
    [[YBBaseAppDelegate sharedAppDelegate]popViewController:YES];
}
#pragma mark--------添加搜索条---------end--------


-(void)setSelClassBtn{
    
    selBtnView = [[UIView alloc]initWithFrame:CGRectMake(0, navi.bottom, _window_width, 40)];
    [self.view addSubview:selBtnView];
    
    newBtn = [UIButton buttonWithType:0];
    newBtn.frame = CGRectMake(12, 10, 60, 20);
    [newBtn setTitle:YZMsg(@"新品") forState:UIControlStateNormal];
    [newBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [newBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    newBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [newBtn addTarget:self action:@selector(newBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [selBtnView addSubview:newBtn];
    
    sellBtn = [UIButton buttonWithType:0];
    sellBtn.frame = CGRectMake(newBtn.right+12, 10, 60, 20);
    [sellBtn setTitle:YZMsg(@"销量") forState:UIControlStateNormal];
    [sellBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [sellBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    sellBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [sellBtn setImage:[UIImage imageNamed:@"sel_up"] forState:UIControlStateSelected];
    [sellBtn setImage:[UIImage imageNamed:@"sel_normal"] forState:UIControlStateNormal];
    sellBtn.titleEdgeInsets = UIEdgeInsetsMake(0,-sellBtn.imageView.frame.size.width, 0, sellBtn.imageView.frame.size.width);
    sellBtn.imageEdgeInsets = UIEdgeInsetsMake(0,sellBtn.titleLabel.bounds.size.width, 0, - sellBtn.titleLabel.bounds.size.width);
    [sellBtn addTarget:self action:@selector(sellBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [selBtnView addSubview:sellBtn];
    
    priceBtn = [UIButton buttonWithType:0];
    priceBtn.frame = CGRectMake(sellBtn.right+12, 10, 60, 20);
    [priceBtn setTitle:YZMsg(@"价格") forState:UIControlStateNormal];
    [priceBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [priceBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    priceBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [priceBtn setImage:[UIImage imageNamed:@"sel_up"] forState:UIControlStateSelected];
    [priceBtn setImage:[UIImage imageNamed:@"sel_normal"] forState:UIControlStateNormal];
    priceBtn.titleEdgeInsets = UIEdgeInsetsMake(0,-priceBtn.imageView.frame.size.width, 0, priceBtn.imageView.frame.size.width);
    priceBtn.imageEdgeInsets = UIEdgeInsetsMake(0,priceBtn.titleLabel.bounds.size.width, 0, - priceBtn.titleLabel.bounds.size.width);
    [priceBtn addTarget:self action:@selector(priceBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [selBtnView addSubview:priceBtn];

    
    changeUIBtn = [UIButton buttonWithType:0];
    changeUIBtn.frame = CGRectMake(selBtnView.width-40, 10, 20, 20);
    [changeUIBtn setImage:[UIImage imageNamed:@"change_横"] forState:UIControlStateNormal];
    [changeUIBtn setImage:[UIImage imageNamed:@"change_竖"] forState:UIControlStateSelected];
    [changeUIBtn addTarget:self action:@selector(changeUIClick) forControlEvents:UIControlEventTouchUpInside];
    [selBtnView addSubview:changeUIBtn];

}
-(void)newBtnClick{
    pageIndex= 1;
    sellIsUp = NO;
    priceIsUp = NO;
    newBtn.selected = YES;
    sellBtn.selected = NO;
    priceBtn.selected =NO;
    
    isnew = @"1";
    sellSortStr = @"";
    priceSortStr = @"";
    [self requestListData];
}
-(void)sellBtnClick{
    pageIndex = 1;
    sellBtn.selected = YES;
    priceBtn.selected =NO;
    newBtn.selected = NO;
    priceIsUp = NO;
    
    sellIsUp = !sellIsUp;
    if (sellIsUp) {
        [sellBtn setImage:[UIImage imageNamed:@"sel_up"] forState:UIControlStateSelected];
        sellSortStr = @"asc";

    }else{
        [sellBtn setImage:[UIImage imageNamed:@"sel_down"] forState:UIControlStateSelected];
        sellSortStr = @"desc";

    }
    isnew = @"0";
    priceSortStr = @"";
    [self requestListData];

}
-(void)priceBtnClick{
    pageIndex = 1;
    sellBtn.selected = NO;
    priceBtn.selected =YES;
    newBtn.selected = NO;
    sellIsUp = NO;
    
    priceIsUp = !priceIsUp;
    if (priceIsUp) {
        [priceBtn setImage:[UIImage imageNamed:@"sel_up"] forState:UIControlStateSelected];
        priceSortStr = @"asc";

    }else{
        [priceBtn setImage:[UIImage imageNamed:@"sel_down"] forState:UIControlStateSelected];
        priceSortStr = @"desc";
    }
    isnew = @"0";
    sellSortStr = @"";
    [self requestListData];

}

-(void)changeUIClick{
    changeUIBtn.selected = !changeUIBtn.selected;
    isVertical = changeUIBtn.selected;
    if (isVertical) {
        flow.itemSize = CGSizeMake(_window_width,118);

    }else{
        flow.itemSize = CGSizeMake((_window_width-21)/2, (_window_width-21)/2 + 75);

    }

    [_collectionView reloadData];
}


-(void)createCollectionView{
        flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake((_window_width-21)/2, (_window_width-21)/2 + 75);
        flow.minimumLineSpacing = 7;
        flow.minimumInteritemSpacing = 7;
        flow.sectionInset = UIEdgeInsetsMake(7, 7, 7, 7);

        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,selBtnView.bottom, _window_width, _window_height-64-statusbarHeight-selBtnView.height) collectionViewLayout:flow];
        _collectionView.backgroundColor = RGB_COLOR(@"#f5f5f5", 1);
        _collectionView.delegate   = self;
        _collectionView.dataSource = self;
        [_collectionView registerNib:[UINib nibWithNibName:@"shopCell" bundle:nil] forCellWithReuseIdentifier:@"shopCELL"];
        [_collectionView registerNib:[UINib nibWithNibName:@"SearchHorizontalCell" bundle:nil] forCellWithReuseIdentifier:@"SearchHorizontalCELL"];

        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hotHeaderV"];
        [self.view addSubview:_collectionView];

        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            pageIndex = 1;
            [self requestListData];
        }];
        _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            pageIndex ++;
            [self requestListData];
        }];
//        [self pullInternet];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _infoArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (isVertical) {
        SearchHorizontalCell *cell = (SearchHorizontalCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"SearchHorizontalCELL" forIndexPath:indexPath];
        NSDictionary *subDic = _infoArray[indexPath.row];
        [cell.thumbImgV sd_setImageWithURL:[NSURL URLWithString:minstr([subDic valueForKey:@"thumb"])]];
        cell.titleL.text = minstr([subDic valueForKey:@"name"]);
        cell.priceL.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"price"])];
        //type  商品类型   0 站内商品  1 外链商品
        if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
            cell.lineLb.hidden = NO;
            cell.sellCountLb.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"original_price"])];
        }else{
            cell.lineLb.hidden = YES;
            cell.sellCountLb.text =[NSString stringWithFormat:@"%@%@%@",YZMsg(@"已售"),minstr([subDic valueForKey:@"sale_nums"]),YZMsg(@"件")];
        }
        
        return cell;

        
    }else{
        ShopCell *cell = (ShopCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"shopCELL" forIndexPath:indexPath];
        NSDictionary *subDic = _infoArray[indexPath.row];
        [cell.thumbImgV sd_setImageWithURL:[NSURL URLWithString:minstr([subDic valueForKey:@"thumb"])]];
        cell.titleL.text = minstr([subDic valueForKey:@"name"]);
        cell.priceL.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"price"])];
        //type  商品类型   0 站内商品  1 外链商品
        if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
            cell.lineLb.hidden = NO;
            cell.sellCountLb.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"original_price"])];
        }else{
            cell.lineLb.hidden = YES;
            cell.sellCountLb.text =[NSString stringWithFormat:@"%@%@%@",YZMsg(@"已售"),minstr([subDic valueForKey:@"sale_nums"]),YZMsg(@"件")];
        }
        
        return cell;

    }
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];

    NSDictionary *subDic = _infoArray[indexPath.row];
    
    [PublicObj checkGoodsExistenceWithID:minstr([subDic valueForKey:@"id"]) Existence:^(int code, NSString *msg) {
        if (code == 0) {
            if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
                OutsideGoodsDetailVC *detail = [[OutsideGoodsDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
                detail.liveUid = @"0";
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

            }else{
                CommodityDetailVC *detail = [[CommodityDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
                detail.liveUid = @"0";
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];
            }
        }else{
            [MBProgressHUD showError:msg];
        }
    }];
}

@end
